package com.example.descentsoundgrid;

import java.lang.reflect.Field;

import AudioHelper.SoundPoolHelper;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.LinearLayout.LayoutParams;

public class MainActivity extends Activity
{
    private SoundPoolHelper mSoundPoolHelper;

    private GridLayout gridLayout;

    private int[] sounds;

    private String packageName;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        gridLayout = (GridLayout) findViewById(R.id.gridLayoutMain);
        gridLayout.setOrientation(0);
        gridLayout.setColumnCount(6);
        gridLayout.setRowCount(0);

        mSoundPoolHelper = new SoundPoolHelper(5, this);

        Field[] fields = R.raw.class.getFields();
        sounds = new int[fields.length];
        packageName = getApplicationContext().getPackageName();

        for (int i = 0; i < fields.length; i++)
        {
            String name = fields[i].getName();
            int id = getResources().getIdentifier(name, "raw", packageName);

            sounds[i] = mSoundPoolHelper.load(this, id, 1);

            Button soundButton = new Button(this);
            soundButton.setText(name);
            soundButton.setWidth(120);

            final int soundId = i;
            soundButton.setOnClickListener(new View.OnClickListener()
            {
                public void onClick(View v)
                {
                    playSound(sounds[soundId]);
                }
            });

            gridLayout.addView(soundButton);

        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;

    }

    private void playSound(int soundId)
    {
        mSoundPoolHelper.play(soundId);
    }

    public void onDestroy()
    {
        mSoundPoolHelper.release();
    }

}
